package com.demo2;

import com.demo2.bean.LicenseInfo;

import java.io.BufferedReader;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.security.KeyFactory;
import java.security.PrivateKey;
import java.security.Signature;
import java.security.spec.PKCS8EncodedKeySpec;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Base64;
import java.util.Properties;

// ========== 3. License生成器 - 使用已有的私钥 ==========
public class LicenseGenerator {
    private static final String ALGORITHM = "RSA";
    private static final String TRANSFORMATION = "RSA/ECB/PKCS1Padding";
    
    private PrivateKey privateKey;
    
    public LicenseGenerator(String privateKeyFilePath) throws Exception {
        this.privateKey = loadPrivateKey(privateKeyFilePath);
        System.out.println("私钥加载成功: " + privateKeyFilePath);
    }
    
    // 从PEM文件加载私钥
    private PrivateKey loadPrivateKey(String filePath) throws Exception {
        StringBuilder keyContent = new StringBuilder();
        
        try (BufferedReader reader = new BufferedReader(new FileReader(filePath))) {
            String line;
            while ((line = reader.readLine()) != null) {
                if (!line.contains("-----")) {
                    keyContent.append(line.trim());
                }
            }
        }
        
        byte[] keyBytes = Base64.getDecoder().decode(keyContent.toString());
        PKCS8EncodedKeySpec spec = new PKCS8EncodedKeySpec(keyBytes);
        KeyFactory keyFactory = KeyFactory.getInstance(ALGORITHM);
        return keyFactory.generatePrivate(spec);
    }
    
    // 生成License文件
    public void generateLicense(LicenseInfo licenseInfo, String outputPath) throws Exception {
        // 1. 生成license内容字符串
        String licenseContent = licenseInfo.toLicenseString();
        System.out.println("License内容:\n" + licenseContent);
        
        // 2. 使用私钥签名license内容
        String signature = signData(licenseContent);
        
        // 3. 创建最终的license文件
        Properties licenseProps = new Properties();
        licenseProps.setProperty("license_data", Base64.getEncoder().encodeToString(licenseContent.getBytes("UTF-8")));
        licenseProps.setProperty("license_signature", signature);
        licenseProps.setProperty("license_version", "2");
        licenseProps.setProperty("license_algorithm", ALGORITHM);
        licenseProps.setProperty("license_generated", LocalDateTime.now().format(DateTimeFormatter.ISO_LOCAL_DATE_TIME));
        
        // 4. 保存license文件
        try (FileOutputStream fos = new FileOutputStream(outputPath)) {
            licenseProps.store(fos, "License File - Generated by LicenseGenerator v2.0");
        }
        
        System.out.println("\nLicense文件已生成: " + outputPath);
        System.out.println("客户: " + licenseInfo.getCustomerName());
        System.out.println("产品: " + licenseInfo.getProductName() + " v" + licenseInfo.getProductVersion());
        System.out.println("到期时间: " + licenseInfo.getExpiryDate());
        System.out.println("最大用户数: " + licenseInfo.getMaxUsers());
    }
    
    // 使用私钥签名数据
    private String signData(String data) throws Exception {
        Signature signature = Signature.getInstance("SHA256withRSA");
        signature.initSign(privateKey);
        signature.update(data.getBytes("UTF-8"));
        byte[] signedData = signature.sign();
        return Base64.getUrlEncoder().withoutPadding().encodeToString(signedData);
    }
}
